package com.example.myapplication;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;

public class SystemControlActivity extends AppCompatActivity {
    private static final int REQUEST_CODE_ENABLE_ADMIN = 1001;
    private SystemControlService systemControlService;
    private ScreenControlService screenControlService;
    private Handler handler;
    private Runnable updateRunnable;

    // UI组件
    private Button btnTurnOffScreen;
    private Button btnTurnOnScreen;
    private Button btnRebootDevice;
    private Button btnShutdownDevice;
    private Button btnInstallApk;
    private EditText editApkPath;
    private TextView textScreenStatus;
    private TextView textMemoryUsage;
    private TextView textSystemUptime;
    private TextView textDeviceInfo;
    private TextView textRootStatus;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_system_control);

        // 初始化服务
        systemControlService = new SystemControlService(this);
        screenControlService = new ScreenControlService(this);

        // 初始化UI组件
        initViews();

        // 设置按钮点击事件
        setupClickListeners();

        // 开始实时更新系统信息
        startRealTimeUpdate();
    }

    private void initViews() {
        btnTurnOffScreen = findViewById(R.id.btn_turn_off_screen);
        btnTurnOnScreen = findViewById(R.id.btn_turn_on_screen);
        btnRebootDevice = findViewById(R.id.btn_reboot_device);
        btnShutdownDevice = findViewById(R.id.btn_shutdown_device);
        btnInstallApk = findViewById(R.id.btn_install_apk);
        editApkPath = findViewById(R.id.edit_apk_path);
        textScreenStatus = findViewById(R.id.text_screen_status);
        textMemoryUsage = findViewById(R.id.text_memory_usage);
        textSystemUptime = findViewById(R.id.text_system_uptime);
        textDeviceInfo = findViewById(R.id.text_device_info);
        textRootStatus = findViewById(R.id.text_root_status);
    }

    private void setupClickListeners() {
        // 关闭屏幕
        btnTurnOffScreen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SystemControlService.SystemControlResult result = systemControlService.turnOffScreen();
                showResult(result);
            }
        });

        // 开启屏幕
        btnTurnOnScreen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SystemControlService.SystemControlResult result = systemControlService.turnOnScreen();
                showResult(result);
            }
        });

        // 重启设备
        btnRebootDevice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SystemControlService.SystemControlResult result = systemControlService.rebootDevice();
                showResult(result);
            }
        });

        // 关机设备
        btnShutdownDevice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SystemControlService.SystemControlResult result = systemControlService.shutdownDevice();
                showResult(result);
            }
        });

        // 安装APK
        btnInstallApk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String apkPath = editApkPath.getText().toString().trim();
                if (apkPath.isEmpty()) {
                    Toast.makeText(SystemControlActivity.this, "请输入APK文件路径", Toast.LENGTH_SHORT).show();
                    return;
                }

                SystemControlService.SystemControlResult result = systemControlService.installApk(apkPath);
                showResult(result);
            }
        });
    }

    private void startRealTimeUpdate() {
        handler = new Handler(Looper.getMainLooper());
        updateRunnable = new Runnable() {
            @Override
            public void run() {
                updateSystemInfo();
                // 每2秒更新一次
                handler.postDelayed(this, 2000);
            }
        };
        handler.post(updateRunnable);
    }

    private void updateSystemInfo() {
        SystemControlService.SystemInfo info = systemControlService.getSystemInfo();

        // 更新屏幕状态
        textScreenStatus.setText("屏幕状态: " + (info.isScreenOn ? "开启" : "关闭"));

        // 更新内存使用情况
        textMemoryUsage.setText(String.format("内存使用: %d%% (%s / %s)",
                info.memoryUsagePercent,
                formatMemorySize(info.totalMemory - info.availableMemory),
                formatMemorySize(info.totalMemory)));

        // 更新系统运行时间
        textSystemUptime.setText("系统运行时间: " + info.systemUptimeFormatted);

        // 更新设备信息
        textDeviceInfo.setText(String.format("设备: %s | Android: %s | API: %d",
                info.deviceModel, info.androidVersion, info.apiLevel));

        // 更新Root权限状态
        textRootStatus.setText("Root权限: " + (info.hasRootPermission ? "已获取" : "未获取"));
        
        // 检查设备管理员权限
        boolean hasDeviceAdmin = screenControlService.isDeviceAdminActive();
        String adminStatus = hasDeviceAdmin ? "已激活" : "未激活";
        textRootStatus.setText("Root权限: " + (info.hasRootPermission ? "已获取" : "未获取") + 
                              " | 设备管理员: " + adminStatus);
        
        // 添加测试权限的点击事件
        textRootStatus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 重新检测root权限
                boolean hasRoot = systemControlService.hasRootPermission();
                boolean hasDeviceAdmin = screenControlService.isDeviceAdminActive();
                
                String message = "Root权限: " + (hasRoot ? "已获取" : "未获取") + 
                               "\n设备管理员: " + (hasDeviceAdmin ? "已激活" : "未激活");
                
                if (!hasDeviceAdmin) {
                    message += "\n\n点击确定请求设备管理员权限";
                }
                
                Toast.makeText(SystemControlActivity.this, message, Toast.LENGTH_LONG).show();
                
                // 如果没有设备管理员权限，请求权限
                if (!hasDeviceAdmin) {
                    requestDeviceAdminPermission();
                }
                
                // 更新显示
                textRootStatus.setText("Root权限: " + (hasRoot ? "已获取" : "未获取") + 
                                      " | 设备管理员: " + (hasDeviceAdmin ? "已激活" : "未激活"));
            }
        });
        
        // 根据Root权限状态更新按钮状态
        boolean hasRoot = info.hasRootPermission;
        btnTurnOffScreen.setEnabled(hasRoot);
        btnTurnOnScreen.setEnabled(hasRoot);
        btnRebootDevice.setEnabled(hasRoot);
        btnShutdownDevice.setEnabled(hasRoot);
        
        // 更新按钮文本提示
        if (!hasRoot) {
            btnTurnOffScreen.setText("关闭屏幕 (需要Root)");
            btnTurnOnScreen.setText("开启屏幕 (需要Root)");
            btnRebootDevice.setText("重启设备 (需要Root)");
            btnShutdownDevice.setText("关机设备 (需要Root)");
        } else {
            btnTurnOffScreen.setText("关闭屏幕");
            btnTurnOnScreen.setText("开启屏幕");
            btnRebootDevice.setText("重启设备");
            btnShutdownDevice.setText("关机设备");
        }
    }


    private void showResult(SystemControlService.SystemControlResult result) {
        String message = result.message;
        if (result.success) {
            Toast.makeText(this, "✓ " + message, Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, "✗ " + message, Toast.LENGTH_LONG).show();
        }
    }

    private String formatMemorySize(long bytes) {
        if (bytes < 1024) {
            return bytes + " B";
        } else if (bytes < 1024 * 1024) {
            return String.format("%.1f KB", bytes / 1024.0);
        } else if (bytes < 1024 * 1024 * 1024) {
            return String.format("%.1f MB", bytes / (1024.0 * 1024.0));
        } else {
            return String.format("%.1f GB", bytes / (1024.0 * 1024.0 * 1024.0));
        }
    }

    /**
     * 请求设备管理员权限
     */
    private void requestDeviceAdminPermission() {
        screenControlService.requestDeviceAdminPermission(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_ENABLE_ADMIN) {
            if (resultCode == RESULT_OK) {
                Toast.makeText(this, "设备管理员权限已激活", Toast.LENGTH_SHORT).show();
                // 重新更新UI
                updateSystemInfo();
            } else {
                Toast.makeText(this, "设备管理员权限激活失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handler != null && updateRunnable != null) {
            handler.removeCallbacks(updateRunnable);
        }
    }
}
